<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="python,">





  <link rel="alternate" href="/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="我没学过python，通过网上和一些图书资料，自学并且记下笔记。 很多细节留作以后自己做项目时再研究，这样能更高效一些。 python基础自学笔记 一、基本输入和输出pthon3.0用input提示用户输入，用print提示用户输出，格式为print(“…”) 如果格式化输出，那么格式为print(&amp;quot;%d&amp;quot; %(变量名)), %d可以替换为%s等其他格式符，以后用到什么格式自己">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="python自学笔记(一)">
<meta property="og:url" content="http://www.limerence2017.com/2017/08/16/python1/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="我没学过python，通过网上和一些图书资料，自学并且记下笔记。 很多细节留作以后自己做项目时再研究，这样能更高效一些。 python基础自学笔记 一、基本输入和输出pthon3.0用input提示用户输入，用print提示用户输出，格式为print(“…”) 如果格式化输出，那么格式为print(&amp;quot;%d&amp;quot; %(变量名)), %d可以替换为%s等其他格式符，以后用到什么格式自己">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/1.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/2.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/3.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/4.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/5.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/6.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/7.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/8.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/16/python1/1.jpg">
<meta property="og:updated_time" content="2020-06-22T09:30:59.009Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python自学笔记(一)">
<meta name="twitter:description" content="我没学过python，通过网上和一些图书资料，自学并且记下笔记。 很多细节留作以后自己做项目时再研究，这样能更高效一些。 python基础自学笔记 一、基本输入和输出pthon3.0用input提示用户输入，用print提示用户输出，格式为print(“…”) 如果格式化输出，那么格式为print(&amp;quot;%d&amp;quot; %(变量名)), %d可以替换为%s等其他格式符，以后用到什么格式自己">
<meta name="twitter:image" content="http://www.limerence2017.com/2017/08/16/python1/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.limerence2017.com/2017/08/16/python1/">





  <title>python自学笔记(一) | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.limerence2017.com/2017/08/16/python1/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python自学笔记(一)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-08-16T16:09:08+08:00">
                2017-08-16
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index">
                    <span itemprop="name">python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>我没学过<code>python</code>，通过网上和一些图书资料，自学并且记下笔记。</p>
<p>很多细节留作以后自己做项目时再研究，这样能更高效一些。</p>
<p>python基础自学笔记</p>
<h2 id="一、基本输入和输出"><a href="#一、基本输入和输出" class="headerlink" title="一、基本输入和输出"></a>一、<code>基本输入和输出</code></h2><p>pthon3.0用input提示用户输入，用print提示用户输出，格式为print(“…”)</p>
<p>如果格式化输出，那么格式为<code>print(&quot;%d&quot; %(变量名))</code>, <code>%d可以替换为%s等其他格式符</code>，以后用到什么格式自己查，这样学起来高效。</p>
<p>简单的例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#-*-coding:utf-8-*-</span></span><br><span class="line">name = input(<span class="string">"What's your name ? &gt;"</span>)</span><br><span class="line">age = input(<span class="string">"How old are you ? &gt;"</span>)</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"your name is %s, your age is %d"</span> %(name, int(age)))</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"你的名字是 %s, 你的年龄是 %d"</span> %(name,int(age)))</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>运行结果：<br><img src="1.png" alt="1.png"></p>
<h2 id="二、基本数据结构"><a href="#二、基本数据结构" class="headerlink" title="二、基本数据结构"></a>二、基本数据结构</h2><p><code>1 列表</code></p>
<p>列表和C++里边的list差不多,插入方式为: <code>list.insert(1,‘小草’);</code></p>
<p>1为要插入元素放在下标为1的位置，‘小草’为要插入的元素,移除元素的方式为：list.pop(3);  指定取出下标为3的元素</p>
<p>list中元素是按照从下标为0开始计算的。如果要计算列表中元素个数可以通过len(list)计算。</p>
<p>下面是个小例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">animals = [<span class="string">"大象"</span>,<span class="string">"猴子"</span>,<span class="string">"蚂蚁"</span>,<span class="string">"豪猪"</span>]</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"动物园有这些动物:"</span>, animals)</span><br><span class="line">lion = <span class="string">"狮子"</span></span><br><span class="line"><span class="keyword">print</span> (<span class="string">"新来了"</span>, lion)</span><br><span class="line">animals.insert(<span class="number">1</span>,lion)</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"动物园有这些动物:"</span>, animals)</span><br><span class="line">animals.pop(<span class="number">3</span>)</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"蚂蚁灭绝了"</span>)</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"动物园有这些动物:"</span>, animals)</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"老虎和狮子交配生了两个小宝宝"</span>)</span><br><span class="line">babies = [<span class="string">"小宝宝1号"</span>, <span class="string">"小宝宝2号"</span>]</span><br><span class="line">animals.insert(<span class="number">2</span>,babies);</span><br><span class="line"><span class="keyword">print</span> (<span class="string">"动物园有这些动物:"</span>, animals)</span><br><span class="line">print(<span class="string">"饲养员给两个小宝宝取了名字"</span>)</span><br><span class="line">animals[<span class="number">2</span>][<span class="number">0</span>]=<span class="string">"小毛"</span></span><br><span class="line">animals[<span class="number">2</span>][<span class="number">1</span>]=<span class="string">"大毛"</span></span><br><span class="line"><span class="keyword">print</span> (<span class="string">"动物园有这些动物:"</span>,animals)</span><br><span class="line">print(<span class="string">"列表中有%d个元素"</span>  %len(animals))</span><br><span class="line">print(<span class="string">"第三个元素包含%d个元素"</span> %len(animals[<span class="number">2</span>]))</span><br></pre></td></tr></table></figure></p>
<p>试着用python 运行上面这个程序</p>
<p><code>2 tuple（元组）</code></p>
<p>tuple定义之后不可修改，理解为不可修改的列表就行了</p>
<p>试着运行下面这个程序，看看结果：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#-*-coding:utf-8-*-</span></span><br><span class="line">nums = (<span class="number">0</span>,<span class="number">1</span>)</span><br><span class="line">print(<span class="string">"nums are"</span>, nums)</span><br><span class="line">another = (<span class="number">0</span>,<span class="number">1</span>,[<span class="number">3</span>,<span class="number">4</span>])</span><br><span class="line">print(<span class="string">"nums are"</span>, another)</span><br><span class="line">another[<span class="number">2</span>][<span class="number">0</span>] = <span class="number">5</span></span><br><span class="line">print(<span class="string">"nums are"</span>, another);</span><br></pre></td></tr></table></figure></p>
<p>为什么another能被修改？因为another[2]指向的是list，接着将list的第一个元素，下表为0的元素赋值为5，这是允许的。</p>
<p><code>3 dict（字典）</code></p>
<p>字典和C++map很相似，但是不完全相同，字典dict可以包含不同类型的key和value,字典的插入方式很简单d[‘韩梅梅’]=23</p>
<p>d为字典定义的变量名，key为‘韩梅梅’, value为23</p>
<p>当字典d中没有‘韩梅梅’这个key，那么就会将key和value插入d</p>
<p>如果调用d[‘韩梅梅’]=22，那么‘韩梅梅’对应的value就为22了</p>
<p>如果字典d中没有‘李磊’这个key，那么调用print(d[‘李磊’])就会提示出错。</p>
<p>所以取元素的时候要记得判断字典中是否有该key对应的value</p>
<p>可以通过get和in判断，下边代码有使用方法。</p>
<p>字典同样调用pop移除元素</p>
<p>d.pop(‘韩梅梅’)</p>
<p>下面这段代码综合了dict使用方式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">infos = &#123;<span class="string">"李明"</span>:<span class="number">23</span>, <span class="string">"豆豆"</span>:<span class="number">22</span>,<span class="string">"老李"</span>:<span class="number">55</span>&#125;</span><br><span class="line">print(<span class="string">"李明的年龄为%d"</span> %(infos[<span class="string">"李明"</span>]))</span><br><span class="line">infos[<span class="string">"王立冬"</span>]=<span class="number">32</span></span><br><span class="line"><span class="keyword">print</span> (infos)</span><br><span class="line"><span class="comment">#print (infos["梁田"])</span></span><br><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> (<span class="string">"梁田"</span> <span class="keyword">in</span> infos):</span><br><span class="line">    print(<span class="string">"梁田不在记录"</span>)</span><br><span class="line">print(infos.get(<span class="string">"梁田"</span>))</span><br><span class="line">print(infos.get(<span class="string">"梁田"</span>,<span class="string">"梁田不在记录"</span>))</span><br><span class="line">infos.pop(<span class="string">"王立冬"</span>)</span><br><span class="line"><span class="keyword">print</span> (infos)</span><br></pre></td></tr></table></figure>
<p>用python调用上边代码，看看效果。</p>
<p><code>4  set（集合）</code></p>
<p>集合中允许存在多个重复的值</p>
<p>集合添加元素用add，删除用remove操作</p>
<p>下边的代码为集合操作<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">numset = set([<span class="number">1</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">7</span>,<span class="number">9</span>])</span><br><span class="line">print(numset)</span><br><span class="line">numset.add(<span class="number">4</span>)</span><br><span class="line">print(numset)</span><br><span class="line">numset.add(<span class="number">4</span>)</span><br><span class="line">print(numset)</span><br><span class="line">numset.remove(<span class="number">3</span>)</span><br><span class="line">print(numset)</span><br><span class="line">numset2 = set([<span class="number">2</span>,<span class="number">4</span>,<span class="number">6</span>,<span class="number">8</span>,<span class="number">10</span>])</span><br><span class="line">print(numset&amp;numset2)</span><br><span class="line">print(numset|numset2)</span><br></pre></td></tr></table></figure></p>
<h2 id="三、循环和控制"><a href="#三、循环和控制" class="headerlink" title="三、循环和控制"></a>三、循环和控制</h2><p>这部分和C++差不多，就是基本写法不一样</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">nums = (<span class="number">0</span>,<span class="number">100</span>,<span class="number">34</span>,<span class="number">50</span>,<span class="number">179</span>,<span class="number">130</span>,<span class="number">27</span>,<span class="number">22</span>)</span><br><span class="line">print(<span class="string">"nums are:"</span>, nums)</span><br><span class="line">bigernums =[]</span><br><span class="line">smallnums = []</span><br><span class="line"><span class="keyword">for</span> num <span class="keyword">in</span> nums:</span><br><span class="line">    <span class="keyword">if</span> num &gt; <span class="number">50</span>:</span><br><span class="line">        bigernums.append(num)</span><br><span class="line">print(<span class="string">"大于50的数字有:"</span>, bigernums)</span><br><span class="line"><span class="keyword">for</span> num <span class="keyword">in</span> nums:</span><br><span class="line">    <span class="keyword">if</span> num &lt; <span class="number">50</span>:</span><br><span class="line">        smallnums.append(num)</span><br><span class="line">print(<span class="string">"小于50的数字有:"</span>, smallnums)</span><br><span class="line">print(range(<span class="number">5</span>))</span><br><span class="line">print(list(range(<span class="number">5</span>)))</span><br><span class="line"><span class="comment">#1~10数字求和</span></span><br><span class="line">sum = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> num <span class="keyword">in</span> list(range(<span class="number">11</span>)):</span><br><span class="line">    sum += num</span><br><span class="line">print(<span class="string">"1到10数字求和结果为:%d"</span> %sum)</span><br><span class="line"><span class="comment">#错误输出</span></span><br><span class="line"><span class="comment">#print("1到10数字求和结果为:%d", sum)</span></span><br><span class="line"><span class="comment">#换一种方式求和,while循环注意别写成死循环</span></span><br><span class="line">i = <span class="number">0</span></span><br><span class="line">sum = <span class="number">0</span></span><br><span class="line"><span class="keyword">while</span> i &lt; <span class="number">11</span>:</span><br><span class="line">    sum += i</span><br><span class="line">    i=i+<span class="number">1</span><span class="comment">#i++不行，习惯了C++</span></span><br><span class="line">print(<span class="string">"1到10数字求和结果为:%d"</span> %sum)</span><br></pre></td></tr></table></figure>
<p>python通过缩进和：控制模块。</p>
<p>四、函数</p>
<p>1 定义函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">judgeint</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> isinstance(x,(int)):</span><br><span class="line">        <span class="keyword">raise</span> TypeError(<span class="string">'类型不匹配'</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> x</span><br></pre></td></tr></table></figure></p>
<p>是通过def 函数名(参数):方式来定义函数。上面这个函数定义在func.py文件中，我再写一个文件使用这个函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> func <span class="keyword">import</span> judgeint</span><br><span class="line">numlist = [<span class="number">1</span>,<span class="number">3</span>,<span class="number">5</span>]</span><br><span class="line">strlist =[<span class="string">'1'</span>,<span class="string">'2'</span>,<span class="string">'3'</span>]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> numlist:</span><br><span class="line">    print(judgeint(i))</span><br><span class="line"><span class="keyword">for</span> j <span class="keyword">in</span> strlist:</span><br><span class="line">    print(strlist(j))</span><br></pre></td></tr></table></figure></p>
<p>结果为：<br><img src="2.png" alt="2.png"><br>可见strlist中字符串类型被函数识别并终止程序运行了。</p>
<p>想用到某个.py文件的函数可以用<code>from 文件名(不包含.py) import 函数名</code></p>
<p><code>如果想用文件中所有的接口</code></p>
<p><code>from 文件名(不包含.py) import *</code></p>
<p>其他的引用方式我也不会，以后遇到了再去查。</p>
<p>也可以去写一个空函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#空函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">emptyfun</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure></p>
<p>pass表示什么都不做。</p>
<p>当然函数可以返回许多值，这些值其实是通过tuple返回的</p>
<p>定义函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#多个返回值</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getposition</span><span class="params">(x,y)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x, y</span><br></pre></td></tr></table></figure></p>
<p>调用这个函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> func <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">num1 = <span class="number">0</span>; num2 = <span class="number">0</span></span><br><span class="line">num1, num2 = getposition(<span class="number">1</span>,<span class="number">3</span>)</span><br><span class="line">print(<span class="string">'num1 is %d, num2 is %d'</span> %(num1,num2))</span><br><span class="line">print(<span class="string">'result is: '</span>, getposition(<span class="number">1</span>,<span class="number">3</span>) )</span><br></pre></td></tr></table></figure></p>
<p>结果为：<br><img src="3.png" alt="3.png"></p>
<p><code>2 函数参数分类和使用</code></p>
<p>1 <code>位置参数</code></p>
<p>位置参数是普通的参数</p>
<p>如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">power</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x*x</span><br></pre></td></tr></table></figure></p>
<p>2 <code>默认参数</code></p>
<p>默认参数提供了参数的默认赋值<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#默认参数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">power</span><span class="params">(x,n = <span class="number">2</span>)</span>:</span></span><br><span class="line">    imul =<span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span>(n &gt; <span class="number">0</span>):</span><br><span class="line">        imul = x*imul</span><br><span class="line">        n = n<span class="number">-1</span></span><br><span class="line">    <span class="keyword">return</span> imul</span><br></pre></td></tr></table></figure></p>
<p>值得注意的是默认参数要指向不可变对象，否则函数重复调用默认参数会被修改<br>def getList(L=[]):<br>    L.append(“end”)<br>    return L<br>重复调用看看结果如何：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#-*-coding:utf-8-*-</span></span><br><span class="line"><span class="keyword">from</span> func <span class="keyword">import</span> *</span><br><span class="line">L=[]</span><br><span class="line">print(getList(L))</span><br><span class="line">print(getList(L))</span><br></pre></td></tr></table></figure>
<p>结果<br><img src="4.png" alt="4.png"><br>可以看出默认参数随着函数调用被修改了，所以尽量不要让默认参数指向可变对象，list就是可变对象。<br>3 <code>可变参数</code></p>
<p>可变参数使用和定义都非常方便</p>
<p>定义：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">calsum</span><span class="params">(*nums)</span>:</span></span><br><span class="line">    sum = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> nums:</span><br><span class="line">        sum = sum+ i</span><br><span class="line">    <span class="keyword">return</span> sum</span><br></pre></td></tr></table></figure></p>
<p>使用：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#-*-coding:utf-8-*-</span></span><br><span class="line"><span class="keyword">from</span> func <span class="keyword">import</span> *</span><br><span class="line">L=[<span class="number">1</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">7</span>,<span class="number">9</span>]</span><br><span class="line">print(calsum(*L))</span><br><span class="line">print(calsum(*range(<span class="number">0</span>,<span class="number">101</span>)))</span><br></pre></td></tr></table></figure></p>
<p>定义可变参数前边加<em>,使用时可以传入list，tuple等，实参前也加</em>即可。</p>
<p>4 <code>关键字参数</code></p>
<p>其实和可变参数类似，关键字参数可以直接传入字典</p>
<p>定义：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getinfo2</span><span class="params">(name, age, **info)</span>:</span></span><br><span class="line">    print(<span class="string">"姓名："</span>, name, <span class="string">"年龄："</span>, age, <span class="string">"其他信息:"</span>, info)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getinfo3</span><span class="params">(name,age,**info)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> <span class="string">'city'</span> <span class="keyword">in</span> info:</span><br><span class="line">        print(<span class="string">"有城市信息"</span>)</span><br><span class="line">    <span class="keyword">if</span> <span class="string">'job'</span> <span class="keyword">in</span> info:</span><br><span class="line">        print(<span class="string">"有工作记录"</span>)</span><br><span class="line">    print(<span class="string">"姓名："</span>, name, <span class="string">"年龄："</span>, age, <span class="string">"其他信息:"</span>, info)</span><br></pre></td></tr></table></figure></p>
<p>定义关键字参数在形参前边加**</p>
<p>使用：在实参前加**表示取出字典中所有内容依次传递给函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> func <span class="keyword">import</span> *</span><br><span class="line">info =&#123;<span class="string">'性别'</span>:<span class="string">'女'</span>,<span class="string">'job'</span>:<span class="string">'学生'</span>,<span class="string">'city'</span>:<span class="string">'上海'</span>&#125;</span><br><span class="line">info2 =&#123;<span class="string">'性别'</span>:<span class="string">'男'</span>,<span class="string">'job'</span>:<span class="string">'工人'</span>,<span class="string">'city'</span>:<span class="string">'北京'</span>&#125;</span><br><span class="line">getinfo2(<span class="string">'韩梅梅'</span>, <span class="number">23</span>, **info)</span><br><span class="line">getinfo3(<span class="string">'李雷'</span>,<span class="number">25</span>,**info2)</span><br></pre></td></tr></table></figure></p>
<p>结果<br><img src="5.png" alt="5.png"><br>5 <code>命名关键字参数</code></p>
<p>命名关键字参数就是传入命名的关键字，如指定传入的关键字参数的key为‘city’，‘type’等等。</p>
<p>举例：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getinfo8</span><span class="params">(name, age, *,city, job)</span>:</span></span><br><span class="line">    print(<span class="string">"姓名："</span>, name, <span class="string">"年龄："</span>, age, <span class="string">"城市:"</span>, city, <span class="string">"工作："</span>, job)</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getinfo7</span><span class="params">(name, age, *infolist, city, job)</span>:</span></span><br><span class="line">    print(<span class="string">"姓名："</span>, name, <span class="string">"年龄："</span>, age, <span class="string">"城市:"</span>, city, <span class="string">"工作："</span>, job, <span class="string">"其他信息:"</span>, infolist)</span><br></pre></td></tr></table></figure></p>
<p>可以看出命名关键字参数格式为(*,指定名称1，指定名称2…)的格式</p>
<p>当命名关键字参数之前的参数为可变参数时，那么不需要*，只需指明指定的几个名成即可</p>
<p>格式为:(*可变参数,指定名称1,指定名称2…)</p>
<p>试着写个代码用一下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> func <span class="keyword">import</span> *</span><br><span class="line">info =&#123;<span class="string">'性别'</span>:<span class="string">'女'</span>,<span class="string">'job'</span>:<span class="string">'学生'</span>,<span class="string">'city'</span>:<span class="string">'上海'</span>&#125;</span><br><span class="line">info2 =&#123;<span class="string">'性别'</span>:<span class="string">'男'</span>,<span class="string">'job'</span>:<span class="string">'工人'</span>,<span class="string">'city'</span>:<span class="string">'北京'</span>&#125;</span><br><span class="line">getinfo2(<span class="string">'韩梅梅'</span>, <span class="number">23</span>, **info)</span><br><span class="line">getinfo3(<span class="string">'李雷'</span>,<span class="number">25</span>,**info2)</span><br><span class="line">getinfo8(<span class="string">'王麻子'</span>,<span class="number">70</span>, city =<span class="string">'南京'</span>, job = <span class="string">'裁缝'</span>)</span><br><span class="line">infolist = [<span class="string">'有犯罪记录'</span>,<span class="string">'酗酒'</span>]</span><br><span class="line">getinfo7(<span class="string">'张三'</span>,<span class="number">50</span>,*infolist,city =<span class="string">'翰林'</span>,job =<span class="string">'无业游民'</span>)</span><br></pre></td></tr></table></figure></p>
<p>读者自己打印下，看看结果<br><img src="6.png" alt="6.png"><br>当然<code>命名关键字参数可以提供默认值</code><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getinfo4</span><span class="params">(name, age,*,city=<span class="string">'沈阳'</span>,job)</span>:</span></span><br><span class="line">    print(<span class="string">"姓名："</span>, name, <span class="string">"年龄："</span>, age, <span class="string">"城市:"</span>, city, <span class="string">"工作："</span>, job)</span><br></pre></td></tr></table></figure></p>
<p>6 <code>参数混合使用</code></p>
<p>当参数列表包含位置参数，默认参数，可变参数，关键字参数和明明关键字参数时，</p>
<p>从左到右的<code>顺序</code>为</p>
<p><code>位置参数</code>，<code>默认参数</code>，<code>可变参数</code>，<code>命名关键字参数</code>，<code>关键字参数</code></p>
<p>读者可以自己考虑下为什么这么规定</p>
<p>下面定义两个函数：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getinfo5</span><span class="params">(name,age,city=<span class="string">'沈阳'</span>,**info)</span>:</span></span><br><span class="line">    print(<span class="string">"姓名："</span>, name, <span class="string">"年龄："</span>, age, <span class="string">"城市:"</span>, city, <span class="string">"其他信息:"</span>, info)</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getinfo6</span><span class="params">(name,age,city=<span class="string">'沈阳'</span>,*infolist ,health = <span class="string">'良好'</span>, job,**otherinfo)</span>:</span></span><br><span class="line">    print(<span class="string">"姓名："</span>, name, <span class="string">"年龄："</span>, age, <span class="string">"城市:"</span>, city, <span class="string">'工作信息：'</span>,job,<span class="string">'\n'</span>,</span><br><span class="line">        <span class="string">"身体状况"</span>, health, <span class="string">"个人备注"</span>,infolist,<span class="string">'\n'</span>,</span><br><span class="line">        <span class="string">"其他信息:"</span>, otherinfo)</span><br></pre></td></tr></table></figure></p>
<p>使用这一系列定义的函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">info5 =&#123;<span class="string">'性别'</span>:<span class="string">'男'</span>,<span class="string">'job'</span>:<span class="string">'工人'</span>,<span class="string">'兴趣'</span>:<span class="string">'修自行车'</span>&#125;</span><br><span class="line">baselist=(<span class="string">'Linkn'</span>,<span class="number">28</span>,<span class="string">'上海'</span>,<span class="string">'喜欢喝冰啤酒'</span>,<span class="string">'爱打麻将'</span>)</span><br><span class="line"></span><br><span class="line">getinfo6(*baselist,**info5)</span><br><span class="line">getinfo5(<span class="string">'Linkn'</span>,<span class="number">28</span>,<span class="string">'上海'</span>,**info5);</span><br></pre></td></tr></table></figure>
<h1 id="函数调用传入实参都可以通过-arg-dict格式，提高了开发效率"><a href="#函数调用传入实参都可以通过-arg-dict格式，提高了开发效率" class="headerlink" title="函数调用传入实参都可以通过*arg,**dict格式，提高了开发效率"></a>函数调用传入实参都可以通过*arg,**dict格式，提高了开发效率</h1><p>7 <code>递归函数</code></p>
<p>递归函数和C++一样，先实现一个阶乘的函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#递归计算阶乘函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">imul2</span><span class="params">(num=<span class="number">1</span>)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> num ==<span class="number">1</span>:</span><br><span class="line">        <span class="keyword">return</span> num</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> num * imul2(num<span class="number">-1</span>)</span><br></pre></td></tr></table></figure></p>
<p>print(imul2(3)) #看看结果<br>同样去实现汉诺塔</p>
<p>编写move(n, a, b, c)函数，它接收参数n，表示3个柱子A、B、C中第1个柱子A的盘子数量，</p>
<p>然后打印出把所有盘子从A借助B移动到C的方法，计算n==3时，移动方法<br><img src="7.png" alt="7.png"></p>
<p>读者试着自己完成，我是这样实现的</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">move</span><span class="params">(n,A,B,C)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> n==<span class="number">1</span>:</span><br><span class="line">        print(<span class="string">"%s --&gt; %s"</span> %(A,C))</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        move(n<span class="number">-1</span>,A,C,B)</span><br><span class="line">        move(<span class="number">1</span>,A,B,C)</span><br><span class="line">        move(n<span class="number">-1</span>,B,A,C)</span><br></pre></td></tr></table></figure>
<p>调用 move(3,’A’,’B’,’C’)</p>
<p>结果为<br><img src="8.png" alt="8.png"><br>用递归很简单实现了复杂的逻辑，但是递归有一个问题就是当递归次数过大容易造成栈溢出。</p>
<p>基础先记到这里，下一篇会记录python的特性和函数编程。</p>
<p>我的公众号，谢谢关注：<br><img src="1.jpg" alt="1.jpg"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"># python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/15/asmend/" rel="next" title="汇编基础最后一篇--机器语言指令">
                <i class="fa fa-chevron-left"></i> 汇编基础最后一篇--机器语言指令
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/17/python2/" rel="prev" title="python自学笔记(二)">
                python自学笔记(二) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、基本输入和输出"><span class="nav-number">1.</span> <span class="nav-text">一、基本输入和输出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、基本数据结构"><span class="nav-number">2.</span> <span class="nav-text">二、基本数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、循环和控制"><span class="nav-number">3.</span> <span class="nav-text">三、循环和控制</span></a></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#函数调用传入实参都可以通过-arg-dict格式，提高了开发效率"><span class="nav-number"></span> <span class="nav-text">函数调用传入实参都可以通过*arg,**dict格式，提高了开发效率</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
